package com.speedchina.common.upload.base;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.csvreader.CsvReader;
import com.speedchina.common.domain.ExcelReadResult;
import com.speedchina.common.download.base.CSVConfiguration;
import com.speedchina.common.download.utils.CsvWriter;
import com.speedchina.framework.utils.JSONUtils;
import com.sun.javafx.collections.MappingChange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * @author ZhangWC
 */
public class BaseListener<T> extends AnalysisEventListener<T> {

    public BaseListener(Class clazz) {
        this.clazz = clazz;
    }
    private Class clazz;

    private static final Logger LOGGER = LoggerFactory.getLogger(BaseListener.class);

    List<T> list = new ArrayList<T>();

    /**
     * 用于存储解析到的数据和基础信息，行号
     */
    private List<ExcelReadResult<T>> excelReadResultList = new ArrayList<ExcelReadResult<T>>();

    private Boolean templateCorrect = true;

    /**
     * 定义接收异常
     */
    private StringBuffer  errorMsg;

    /**
     * 这个每一条数据解析都会来调用
     * author: xz
     * date: 2021/6/25 14:00
     * [data, context]
     * @return void
     */
    @Override
    public void invoke(T data, AnalysisContext context) {
        LOGGER.info("解析到一条数据:{}", JSONUtils.toJSONString(data));
        list.add(data);
        //多封装一个返回值用作于放行号
        ReadRowHolder readRowHolder = context.readRowHolder();
        ExcelReadResult excelReadResult = new ExcelReadResult(context.readRowHolder().getRowIndex() + 1,data);
        excelReadResultList.add(excelReadResult);
    }
    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        LOGGER.info("所有数据解析完成！");
    }

    /**
     * 在转换异常 获取其他异常下会调用本接口。抛出异常则停止读取。如果这里不抛出异常则 继续读取下一行。
     *
     * @param exception
     * @param context
     * @throws Exception
     */
    @Override
    public void onException(Exception exception, AnalysisContext context) {
        LOGGER.error("解析失败，但是继续解析下一行:{}", exception.getMessage());
        // 如果是某一个单元格的转换异常 能获取到具体行号
        // 如果要获取头的信息 配合invokeHeadMap使用
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException)exception;
            LOGGER.error("第{}行，第{}列解析异常，数据为:{}", excelDataConvertException.getRowIndex(),
                    excelDataConvertException.getColumnIndex(), excelDataConvertException.getCellData());
            String msg="第"+excelDataConvertException.getRowIndex()+"行，第"
                    + excelDataConvertException.getColumnIndex()+"列解析异常，数据为:"
                    + excelDataConvertException.getCellData();
            if(errorMsg==null){
                errorMsg=new StringBuffer();
            }
            //拼接报错信息
            errorMsg.append(msg).append(System.lineSeparator());
        }

    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        System.out.println(headMap);
        List<CSVConfiguration> csvConfiguration = CsvWriter.getCSVConfiguration(clazz);
        for (CSVConfiguration configuration : csvConfiguration) {
            if (!configuration.getHead().equals(headMap.get(configuration.getOrder()))){
                templateCorrect = false;
            }
        }
    }

    public List<ExcelReadResult<T>> getExcelReadResultList(){
        return excelReadResultList;
    }

    public Boolean getTemplateCorrect(){
        return templateCorrect;
    }
}